package com.jie.component.threadpool;

import com.jie.component.threadpool.core.BaseThreadPool;
import com.jie.component.threadpool.factory.BusinessNameThreadFactory;
import com.jie.component.threadpool.rejectedexecutionhandler.ThreadPoolRejectedExecutionHandler;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.*;

/**
 * @author jie
 * @version 1.0 2025-02-13
 */
public class BusinessThreadPool extends BaseThreadPool {

    private static ThreadPoolExecutor executor = null;

    static {
        executor = new ThreadPoolExecutor(

                Runtime.getRuntime().availableProcessors() + 1,

                maximumPoolSize(),

                60,

                TimeUnit.SECONDS,

                new ArrayBlockingQueue<>(600),

                new BusinessNameThreadFactory(),

                new ThreadPoolRejectedExecutionHandler.BusinessAbortPolicy());
    }

    private static Integer maximumPoolSize() {
        return new BigDecimal(Runtime.getRuntime().availableProcessors())
                .divide(new BigDecimal("0.2"), 0, RoundingMode.HALF_UP).intValue();
    }

    public static void execute(Runnable r) {
        executor.execute(wrapTask(r, getContextForTask(), getContextForHold()));
    }

    public static <T> Future<T> submit(Callable<T> c) {
        return executor.submit(wrapTask(c, getContextForTask(), getContextForHold()));
    }
}
